package com.sjh.tomcat.handler;

import com.sjh.servlet.CalServlet;
import com.sjh.tomcat.SjhTomcatV3;
import com.sjh.tomcat.http.SjhRequest;
import com.sjh.tomcat.http.SjhResponse;
import com.sjh.tomcat.servlet.SjhCalServlet;
import com.sjh.tomcat.servlet.SjhHttpServlet;

import java.io.*;
import java.net.Socket;

public class SjhRequestHandler implements Runnable{

    //该线程类完成的任务需要操作socket
    private Socket socket = null;

    public SjhRequestHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() { // 在Run方法中编写线程任务，完成对客户端/浏览器IO
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            SjhRequest sjhRequest = new SjhRequest(inputStream);
            SjhResponse sjhResponse = new SjhResponse(outputStream);
            

            // 从容器中获取Servlet
            String uri = sjhRequest.getUri();
            String servletName = SjhTomcatV3.servletUrlMapping.get(uri);
            if(servletName != null){
                SjhHttpServlet sjhHttpServlet = SjhTomcatV3.servletMapping.get(servletName);
                sjhHttpServlet.service(sjhRequest, sjhResponse);
            }else{
                String resp = SjhResponse.respHeader + "<h1>404 NOt FOUND</h1>";
                sjhResponse.getOutputStream().write(resp.getBytes());
                outputStream.write(resp.getBytes());
                outputStream.flush();
                outputStream.close();
            }
            inputStream.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
